package top.dotgo.web.admin.oauth.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.aliyun.oss.common.utils.IOUtils;
import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.dotgo.kit.ex.DotMsg;
import top.dotgo.kit.oss.OssPutKti;
import top.dotgo.kit.oss.OssStsKit;
import top.dotgo.web.base.BaseController;
import top.dotgo.web.base.R;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * oss文件服务
 *
 * @author：jornl
 * @date : 2019/3/5 1:05
 */
@RequestMapping("/api/oss")
@Controller
public class OssController extends BaseController {

    /**
     * 获取oss上传临时密钥
     *
     * @return R
     */
    @GetMapping(value = {"/v1/sts"})
    @ResponseBody
    public R getSts() {
        return R.ok()
                .put("sts", OssStsKit.get().getStsToken())
                .put("region", OssStsKit.REGION)
                .put("bucket", OssStsKit.BUCKET);
    }

    /**
     * 根据oss文件路径获取真实文件
     *
     * @param token   token
     * @param ossPath ossPath
     * @param process process
     */
    @GetMapping(value = {"/v1/url"})
    public void getTempImg(HttpServletResponse response,
                           @RequestParam String token,
                           @RequestParam String ossPath,
                           @RequestParam(required = false) String process) throws IOException {
        response.sendRedirect(OssStsKit.get().getTempUrl(ossPath, process));
    }

    /**
     * 生成二维码, 并返回 oss 文件路径
     *
     * @param val    val
     * @param width  width
     * @param height height
     */
    @GetMapping("/v1/qr")
    @ResponseBody
    public R getQrImg(
            @RequestParam String val,
            @RequestParam(defaultValue = "300") Integer width,
            @RequestParam(defaultValue = "300") Integer height) {
        //
        byte[] bytes = QrCodeUtil.generatePng(val, width, height);
        String fileKey = "qr/" + StrUtil.uuid() + ".png";
        OssPutKti.get().putBytes(bytes, fileKey);

        return R.ok(fileKey);
    }


    /**
     * 文件上传接口
     *
     * @param path path
     * @param file file
     * @return key：文件的oss路径
     */
    @SneakyThrows
    @PostMapping("/v1/up/{path}")
    @ResponseBody
    public R upload(@PathVariable(required = false) String path, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.err(DotMsg.PARAM_ERR, "上传失败，请选择文件");
        }

        byte[] bs = IOUtils.readStreamAsByteArray(file.getInputStream());

        String fileKey = getFileKey(path, file.getOriginalFilename());
        OssPutKti.get().putBytes(bs, fileKey);

        return R.ok().put("key", fileKey);
    }

}
